package com.nxw.springcloud.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.nxw.springcloud.admin.config.RedisConfigs;
import com.nxw.springcloud.admin.entity.DynamicVersion;
import com.nxw.springcloud.admin.entity.GatewayRoutes;
import com.nxw.springcloud.admin.respository.DynamicVersionDao;
import com.nxw.springcloud.admin.service.inf.IDynamicVersionService;
import com.nxw.springcloud.admin.service.inf.IRoutesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class DynamicVersionServiceImpl implements IDynamicVersionService {

    @Autowired private DynamicVersionDao mapper;
    @Autowired private StringRedisTemplate redisTemplate;
    @Autowired private IRoutesService routesService;

    @Override
    public DynamicVersion add(DynamicVersion version) {
        version.setCreateTime(new Date());
        DynamicVersion result = mapper.save(version);

        //发布时，把版本信息与路由信息存入redis
        redisTemplate.opsForValue().set(RedisConfigs.versionKey , String.valueOf(version.getId()));
        redisTemplate.opsForValue().set(RedisConfigs.routeKey , JSON.toJSONString(routesService.getRouteDefinitions()));
        GatewayRoutes route = new GatewayRoutes();
        route.setIsDel(false);
        route.setIsEbl(false);
        List<GatewayRoutes> routes = routesService.getRoutes(route);
        for (GatewayRoutes gatewayRoutes : routes) {
            redisTemplate.opsForValue().set(RedisConfigs.rateLimitKey + gatewayRoutes.getRouteId(), JSON.toJSONString(gatewayRoutes.getRatelimitDefinition()));
        }
        return result;
    }

    @Override
    public DynamicVersion update(DynamicVersion version) {
        return mapper.save(version);
    }

    @Override
    public void delete(Long id) {
         mapper.deleteById(id);
    }

    /**
     * 获取最后一次发布的版本号
     * @return
     */
    @Override
    public Long getLastVersion() {
        return mapper.getLastVersion();
    }

    @Override
    public List<DynamicVersion> listAll() {
        return mapper.findAll();
    }
}
